package com.example.starter.util;

import com.example.starter.jackson.module.JavaTimeModule;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Getter;
import lombok.SneakyThrows;


/**
 * @author 王令
 * @since 2022/9/19 8:41
 */
public class JSONUtil {

    @Getter
    private static final ObjectMapper instance;

    static {
        instance = new ObjectMapper();
        final JavaTimeModule javaTimeModule = new JavaTimeModule();
        instance.registerModule(javaTimeModule);
    }

    @SneakyThrows
    public static String toJsonStr(Object o) {
        return instance.writeValueAsString(o);
    }

    @SneakyThrows
    public static byte[] toJsonByte(Object o) {
        return instance.writeValueAsBytes(o);
    }

    public static <T> T parse(byte[] bytes, Class<T> clazz) {
        try {
            return instance.readValue(bytes, clazz);
        } catch (Throwable e) {
            return null;
        }
    }

    public static JsonNode parse(String json) {
        try {
            return instance.readTree(json);
        } catch (Throwable e) {
            return null;
        }
    }

    public static <T> T parse(String json, Class<T> clazz) {
        try {
            return instance.readValue(json, clazz);
        } catch (Throwable e) {
            return null;
        }
    }

    public static <T> T parse(String json, TypeReference<T> typeReference) {
        try {
            return instance.readValue(json, typeReference);
        } catch (Throwable e) {
            return null;
        }
    }

}
